"""
字典管理主界面 - 统一样式版本
"""

import logging
from typing import Dict, Any, List
from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
    QTableWidget, QTableWidgetItem, QHeaderView,
    QPushButton, QLabel, QLineEdit, QComboBox,
    QGroupBox, QSplitter, QTextEdit, QMessageBox,
    QProgressBar, QFrame, QTabWidget, QTreeWidget,
    QTreeWidgetItem, QMenu, QAction
)
from PyQt5.QtCore import Qt, pyqtSignal, QTimer
from PyQt5.QtGui import QFont, QColor

from src.app.modules.dictionary.service import DictionaryService
from src.app.modules.dictionary.utils import DictionaryUtils
from .dictionary_dialog import DictionaryDialog

logger = logging.getLogger(__name__)

class DictionaryWidget(QWidget):
    """字典管理主界面"""
    
    # 信号定义
    status_message = pyqtSignal(str)
    dictionary_changed = pyqtSignal()
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.service = DictionaryService()
        self.utils = DictionaryUtils()
        self.current_type = None
        self.current_data = []
        self.tree_data = {}
        
        # 初始化UI
        self.init_ui()
        
        # 设置定时刷新
        self.refresh_timer = QTimer()
        self.refresh_timer.timeout.connect(self.refresh_statistics)
        self.refresh_timer.start(30000)  # 30秒刷新一次
        
        # 延迟加载数据
        QTimer.singleShot(100, self.load_types)
    
    def init_ui(self):
        """初始化UI界面"""
        layout = QVBoxLayout(self)
        
        # 创建分割器
        splitter = QSplitter(Qt.Vertical)
        layout.addWidget(splitter)
        
        # 上部分：统计信息和筛选
        top_widget = self.create_top_widget()
        splitter.addWidget(top_widget)
        
        # 下部分：字典列表和详情
        bottom_widget = self.create_bottom_widget()
        splitter.addWidget(bottom_widget)
        
        # 设置分割器比例
        splitter.setSizes([200, 500])
    
    def create_top_widget(self):
        """创建上部分组件"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 统计信息组
        stats_group = QGroupBox("字典统计")
        stats_layout = QGridLayout(stats_group)
        
        # 总数统计
        self.total_count_label = QLabel("0")
        self.total_count_label.setStyleSheet("font-size: 24px; font-weight: bold; color: #2196F3;")
        stats_layout.addWidget(QLabel("字典总数:"), 0, 0)
        stats_layout.addWidget(self.total_count_label, 0, 1)
        
        # 按类型统计
        self.type_stats_label = QLabel("加载中...")
        stats_layout.addWidget(QLabel("类型分布:"), 0, 2)
        stats_layout.addWidget(self.type_stats_label, 0, 3)
        
        # 按系统/用户统计
        self.system_user_stats_label = QLabel("加载中...")
        stats_layout.addWidget(QLabel("系统/用户:"), 1, 0)
        stats_layout.addWidget(self.system_user_stats_label, 1, 1)
        
        # 树形结构统计
        self.tree_stats_label = QLabel("加载中...")
        stats_layout.addWidget(QLabel("树形结构:"), 1, 2)
        stats_layout.addWidget(self.tree_stats_label, 1, 3)
        
        layout.addWidget(stats_group)
        
        # 筛选组
        filter_group = QGroupBox("筛选条件")
        filter_layout = QGridLayout(filter_group)
        
        # 字典类型筛选
        filter_layout.addWidget(QLabel("字典类型:"), 0, 0)
        self.dictionary_type_combo = QComboBox()
        self.dictionary_type_combo.addItem("全部")
        self.dictionary_type_combo.currentTextChanged.connect(self.apply_filters)
        filter_layout.addWidget(self.dictionary_type_combo, 0, 1)
        
        # 搜索框
        filter_layout.addWidget(QLabel("字典名称:"), 0, 2)
        self.name_search_edit = QLineEdit()
        self.name_search_edit.setPlaceholderText("输入字典名称搜索")
        self.name_search_edit.textChanged.connect(self.apply_filters)
        filter_layout.addWidget(self.name_search_edit, 0, 3)
        
        # 操作按钮
        button_layout = QHBoxLayout()
        
        self.refresh_btn = QPushButton("刷新")
        self.refresh_btn.clicked.connect(self.refresh_data)
        button_layout.addWidget(self.refresh_btn)
        
        self.export_btn = QPushButton("导出")
        self.export_btn.clicked.connect(self.export_data)
        button_layout.addWidget(self.export_btn)
        
        self.clear_filter_btn = QPushButton("清除筛选")
        self.clear_filter_btn.clicked.connect(self.clear_filters)
        button_layout.addWidget(self.clear_filter_btn)
        
        button_layout.addStretch()
        
        filter_layout.addLayout(button_layout, 1, 0, 1, 4)
        
        layout.addWidget(filter_group)
        
        return widget
    
    def create_bottom_widget(self):
        """创建下部分组件"""
        widget = QWidget()
        layout = QHBoxLayout(widget)
        
        # 左侧：字典列表
        left_widget = self.create_dictionary_list_widget()
        layout.addWidget(left_widget, 2)
        
        # 右侧：字典详情
        right_widget = self.create_dictionary_detail_widget()
        layout.addWidget(right_widget, 1)
        
        return widget
    
    def create_dictionary_list_widget(self):
        """创建字典列表组件"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 标题和操作按钮
        title_layout = QHBoxLayout()
        
        title_label = QLabel("字典列表")
        title_font = QFont()
        title_font.setBold(True)
        title_font.setPointSize(12)
        title_label.setFont(title_font)
        title_layout.addWidget(title_label)
        
        title_layout.addStretch()
        
        self.add_btn = QPushButton("新增字典")
        self.add_btn.clicked.connect(self.add_dictionary)
        title_layout.addWidget(self.add_btn)
        
        self.edit_btn = QPushButton("编辑字典")
        self.edit_btn.clicked.connect(self.edit_dictionary)
        self.edit_btn.setEnabled(False)
        title_layout.addWidget(self.edit_btn)
        
        self.delete_btn = QPushButton("删除字典")
        self.delete_btn.clicked.connect(self.delete_dictionary)
        self.delete_btn.setEnabled(False)
        title_layout.addWidget(self.delete_btn)
        
        layout.addLayout(title_layout)
        
        # 字典表格
        self.dictionary_table = QTableWidget()
        self.dictionary_table.setColumnCount(5)
        self.dictionary_table.setHorizontalHeaderLabels([
            "字典名称", "字典代码", "字典类型", "系统字典", "描述"
        ])
        
        # 设置表格属性
        header = self.dictionary_table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.Stretch)
        header.setSectionResizeMode(1, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(2, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(3, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(4, QHeaderView.ResizeToContents)
        
        self.dictionary_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.dictionary_table.setSelectionMode(QTableWidget.SingleSelection)
        self.dictionary_table.itemSelectionChanged.connect(self.on_selection_changed)
        self.dictionary_table.itemDoubleClicked.connect(self.edit_dictionary)
        
        layout.addWidget(self.dictionary_table)
        
        return widget
    
    def create_dictionary_detail_widget(self):
        """创建字典详情组件"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 标题
        title_label = QLabel("字典详情")
        title_font = QFont()
        title_font.setBold(True)
        title_font.setPointSize(12)
        title_label.setFont(title_font)
        layout.addWidget(title_label)
        
        # 详情标签页
        self.detail_tabs = QTabWidget()
        layout.addWidget(self.detail_tabs)
        
        # 基本信息标签页
        basic_widget = QWidget()
        basic_layout = QVBoxLayout(basic_widget)
        
        self.basic_info_text = QTextEdit()
        self.basic_info_text.setReadOnly(True)
        basic_layout.addWidget(self.basic_info_text)
        
        self.detail_tabs.addTab(basic_widget, "基本信息")
        
        # 树形结构标签页
        tree_widget = QWidget()
        tree_layout = QVBoxLayout(tree_widget)
        
        self.tree_widget = QTreeWidget()
        self.tree_widget.setHeaderLabels(["名称", "代码", "类型"])
        self.tree_widget.itemClicked.connect(self.on_tree_item_clicked)
        
        # 设置列宽
        self.tree_widget.setColumnWidth(0, 150)
        self.tree_widget.setColumnWidth(1, 100)
        self.tree_widget.setColumnWidth(2, 80)
        
        tree_layout.addWidget(self.tree_widget)
        
        self.detail_tabs.addTab(tree_widget, "树形结构")
        
        return widget
    
    def load_types(self):
        """加载字典类型"""
        try:
            types = self.service.get_all_types()
            self.dictionary_type_combo.clear()
            self.dictionary_type_combo.addItem("全部")
            for dict_type in types:
                self.dictionary_type_combo.addItem(dict_type)
            
            # 加载数据
            self.load_dictionaries()
            self.update_statistics()
            
        except Exception as e:
            logger.error(f"加载字典类型失败: {e}")
            QMessageBox.critical(self, "错误", f"加载字典类型失败: {str(e)}")
    
    def load_dictionaries(self):
        """加载字典数据"""
        try:
            self.status_message.emit("正在加载字典数据...")
            
            # 获取筛选条件
            filters = self.get_filter_conditions()
            
            # 获取字典数据
            dictionaries = self.service.get_all_dictionaries(filters)
            self.current_data = dictionaries
            
            # 更新表格
            self.update_dictionary_table(dictionaries)
            
            # 更新树形结构
            self.update_tree_structure(dictionaries)
            
            self.status_message.emit(f"已加载 {len(dictionaries)} 个字典")
            
        except Exception as e:
            logger.error(f"加载字典数据失败: {e}")
            QMessageBox.critical(self, "错误", f"加载数据失败: {str(e)}")
            self.status_message.emit("加载数据失败")
    
    def get_filter_conditions(self):
        """获取筛选条件"""
        filters = {}
        
        # 字典类型
        if self.dictionary_type_combo.currentText() != "全部":
            filters['dict_type'] = self.dictionary_type_combo.currentText()
        
        # 名称搜索
        name_search = self.name_search_edit.text().strip()
        if name_search:
            filters['dict_name'] = name_search
        
        return filters
    
    def update_dictionary_table(self, dictionaries):
        """更新字典表格"""
        self.dictionary_table.setRowCount(len(dictionaries))
        
        for row, dictionary in enumerate(dictionaries):
            # 字典名称
            name_item = QTableWidgetItem(dictionary['dict_name'])
            name_item.setData(Qt.UserRole, dictionary['dict_id'])
            self.dictionary_table.setItem(row, 0, name_item)
            
            # 字典代码
            self.dictionary_table.setItem(row, 1, QTableWidgetItem(dictionary['dict_code']))
            
            # 字典类型
            self.dictionary_table.setItem(row, 2, QTableWidgetItem(dictionary['dict_type']))
            
            # 系统字典
            is_system = "是" if dictionary.get('is_system', False) else "否"
            self.dictionary_table.setItem(row, 3, QTableWidgetItem(is_system))
            
            # 描述
            description = dictionary.get('description', '')
            self.dictionary_table.setItem(row, 4, QTableWidgetItem(description))
    
    def update_tree_structure(self, dictionaries):
        """更新树形结构"""
        self.tree_widget.clear()
        
        # 构建树形数据
        self.tree_data = {}
        root_items = {}
        
        # 第一遍：创建所有节点
        for dictionary in dictionaries:
            item = QTreeWidgetItem(self.tree_widget)
            item.setText(0, dictionary['dict_name'])
            item.setText(1, dictionary['dict_code'])
            item.setText(2, dictionary['dict_type'])
            item.setData(0, Qt.UserRole, dictionary['dict_id'])
            
            self.tree_data[dictionary['dict_id']] = {
                'item': item,
                'data': dictionary,
                'children': []
            }
            
            if not dictionary.get('parent_code'):
                root_items[dictionary['dict_id']] = item
        
        # 第二遍：建立父子关系
        for dictionary in dictionaries:
            parent_code = dictionary.get('parent_code')
            if parent_code and parent_code in self.tree_data:
                # 找到父节点
                for dict_data in self.tree_data.values():
                    if dict_data['data']['dict_code'] == parent_code:
                        parent_item = dict_data['item']
                        child_item = self.tree_data[dictionary['dict_id']]['item']
                        parent_item.addChild(child_item)
                        break
        
        # 展开所有节点
        self.tree_widget.expandAll()
    
    def update_statistics(self):
        """更新统计信息"""
        try:
            stats = self.service.get_statistics()
            
            # 总数
            self.total_count_label.setText(str(stats.get('total_count', 0)))
            
            # 类型分布
            type_stats = stats.get('by_type', {})
            type_text = ", ".join([f"{k}:{v}" for k, v in type_stats.items()])
            self.type_stats_label.setText(type_text if type_text else "无")
            
            # 系统/用户分布
            system_count = stats.get('system_count', 0)
            user_count = stats.get('user_count', 0)
            self.system_user_stats_label.setText(f"系统:{system_count}/用户:{user_count}")
            
            # 树形结构统计
            tree_count = stats.get('tree_count', 0)
            self.tree_stats_label.setText(f"树形节点:{tree_count}")
            
        except Exception as e:
            logger.error(f"更新统计信息失败: {e}")
    
    def refresh_statistics(self):
        """刷新统计信息"""
        self.update_statistics()
    
    def apply_filters(self):
        """应用筛选条件"""
        self.load_dictionaries()
    
    def clear_filters(self):
        """清除筛选条件"""
        self.dictionary_type_combo.setCurrentIndex(0)
        self.name_search_edit.clear()
        self.load_dictionaries()
    
    def on_selection_changed(self):
        """选择改变事件"""
        selected_items = self.dictionary_table.selectedItems()
        has_selection = len(selected_items) > 0
        
        self.edit_btn.setEnabled(has_selection)
        self.delete_btn.setEnabled(has_selection)
        
        if has_selection:
            dict_id = selected_items[0].data(Qt.UserRole)
            self.show_dictionary_detail(dict_id)
        else:
            self.clear_dictionary_detail()
    
    def show_dictionary_detail(self, dict_id):
        """显示字典详情"""
        try:
            dictionary = self.service.get_dictionary_by_id(dict_id)
            if not dictionary:
                return
            
            # 基本信息
            basic_info = f"""
字典ID: {dictionary['dict_id']}
字典名称: {dictionary['dict_name']}
字典代码: {dictionary['dict_code']}
字典类型: {dictionary['dict_type']}
父节点代码: {dictionary.get('parent_code', '无')}
系统字典: {'是' if dictionary.get('is_system', False) else '否'}
排序: {dictionary.get('sort_order', 0)}
描述: {dictionary.get('description', '无')}
创建时间: {dictionary.get('create_time', '无')}
更新时间: {dictionary.get('update_time', '无')}
            """.strip()
            self.basic_info_text.setText(basic_info)
            
        except Exception as e:
            logger.error(f"显示字典详情失败: {e}")
    
    def clear_dictionary_detail(self):
        """清除字典详情"""
        self.basic_info_text.clear()
    
    def add_dictionary(self):
        """新增字典"""
        # 获取当前选中的字典类型，如果没有则使用默认值
        current_type = self.dictionary_type_combo.currentText()
        if current_type == "全部":
            current_type = ""
        
        dialog = DictionaryDialog(parent=self, parent_code=current_type)
        dialog.dictionary_saved.connect(self.on_dictionary_saved)
        dialog.exec_()
    
    def edit_dictionary(self):
        """编辑字典"""
        selected_items = self.dictionary_table.selectedItems()
        if not selected_items:
            return
        
        dict_id = selected_items[0].data(Qt.UserRole)
        dictionary_data = self.service.get_dictionary_by_id(dict_id)
        if not dictionary_data:
            return
        
        dialog = DictionaryDialog(parent=self, dict_id=dict_id)
        dialog.dictionary_saved.connect(self.on_dictionary_saved)
        dialog.exec_()
    
    def delete_dictionary(self):
        """删除字典"""
        selected_items = self.dictionary_table.selectedItems()
        if not selected_items:
            return
        
        dict_id = selected_items[0].data(Qt.UserRole)
        dict_name = selected_items[0].text()
        
        reply = QMessageBox.question(
            self, "确认删除",
            f"确定要删除字典 '{dict_name}' 吗？\n\n注意：如果有子字典，将无法删除。",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            try:
                result = self.service.delete_dictionary(dict_id)
                if result['success']:
                    QMessageBox.information(self, "成功", result['message'])
                    self.load_dictionaries()
                    self.dictionary_changed.emit()
                else:
                    QMessageBox.warning(self, "失败", result['message'])
            except Exception as e:
                logger.error(f"删除字典失败: {e}")
                QMessageBox.critical(self, "错误", f"删除失败: {str(e)}")
    
    def on_dictionary_saved(self, dict_id):
        """字典保存事件"""
        self.load_dictionaries()
        self.dictionary_changed.emit()
    
    def refresh_data(self):
        """刷新数据"""
        self.load_types()
    
    def export_data(self):
        """导出数据"""
        try:
            filters = self.get_filter_conditions()
            data = self.service.export_dictionaries(filters)
            
            if not data:
                QMessageBox.information(self, "提示", "没有数据可导出")
                return
            
            # 这里可以实现导出到Excel的功能
            # 暂时显示导出数据量
            QMessageBox.information(self, "导出成功", f"已导出 {len(data)} 条字典数据")
            
        except Exception as e:
            logger.error(f"导出字典数据失败: {e}")
            QMessageBox.critical(self, "错误", f"导出失败: {str(e)}")
    
    def on_tree_item_clicked(self, item, column):
        """树形节点点击事件"""
        dict_id = item.data(0, Qt.UserRole)
        if dict_id:
            # 在表格中选中对应的字典
            for row in range(self.dictionary_table.rowCount()):
                item = self.dictionary_table.item(row, 0)
                if item and item.data(Qt.UserRole) == dict_id:
                    self.dictionary_table.selectRow(row)
                    break